//
//  DailyKChartViewController.m
//  Stock
//
//  Created by sun black on 12-2-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DailyKChartViewController.h"

@implementation DailyKChartViewController

@synthesize graph;
@synthesize graphHost;
@synthesize datas;
@synthesize service;
@synthesize chartType;
@synthesize stockId;
@synthesize loadingView;

-(void)dealloc
{
    self.graph = nil;
    self.graphHost = nil;
    self.datas = nil;
    [self.service cancleAllRequest];
    self.service = nil;
    self.chartType = nil;
    self.stockId = nil;
    self.loadingView = nil;
    SAFE_RELEASE(greenLine);
    SAFE_RELEASE(redLine);
    [super dealloc];
}
-(void)viewDidUnload{
    self.graph = nil;
    self.graphHost = nil;
    self.datas = nil;
    [self.service cancleAllRequest];
    self.service = nil;
    self.chartType = nil;
    self.stockId = nil;
    self.loadingView = nil;
    SAFE_RELEASE(greenLine);
    SAFE_RELEASE(redLine);
    [super viewDidUnload];
}

-(void)setView:(UIView *)aView;
{
    [super setView:aView];
    if ( nil == aView ) {
        self.graph = nil;
        self.graphHost = nil;
    }
}

-(void) chartViewDidDisplay{
    if (loaded) {
        return;
    }
    [self.service queryDataWithChartType:self.chartType andStockId:self.stockId];
}

-(void)viewDidLoad 
{    
    
    greenLine = [[CPTMutableLineStyle lineStyle] retain];
    greenLine.lineColor = [CPTColor greenColor];
    greenLine.lineWidth = 1.0f;
    
    redLine = [[CPTMutableLineStyle lineStyle] retain];
    redLine.lineColor = [CPTColor redColor];
    redLine.lineWidth = 1.0f;
    
	graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
	CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
	[graph applyTheme:theme];
	
    graph.frame = self.view.bounds;
    
    graph.plotAreaFrame.borderLineStyle = nil;
    graph.plotAreaFrame.borderWidth = 0.0f;
    graph.plotAreaFrame.cornerRadius = 0.0f;
    graph.plotAreaFrame.paddingLeft = 25.0f;
    graph.plotAreaFrame.paddingRight = 0.0f;
    graph.plotAreaFrame.paddingTop = 0.0f;
    graph.plotAreaFrame.paddingBottom = 20.0f;
    
    graph.paddingLeft = 0.0f;
    graph.paddingRight = 0.0f;
    graph.paddingTop = 0.0f;
    graph.paddingBottom = 0.0f;
    
    self.graphHost.hostedGraph = graph;
    
    // Axes
    CPTXYAxisSet *xyAxisSet = (id)graph.axisSet;
    CPTXYAxis *xAxis = xyAxisSet.xAxis;
    CPTMutableLineStyle *lineStyle = [xAxis.axisLineStyle mutableCopy];
    lineStyle.lineCap = kCGLineCapButt;
    xAxis.axisLineStyle = lineStyle;
	[lineStyle release];
    xAxis.labelingPolicy = CPTAxisLabelingPolicyNone;
    CPTMutableTextStyle *textStyle = [CPTTextStyle textStyle];
    textStyle.color = [CPTColor whiteColor];
    textStyle.fontSize = 9.0f;
    textStyle.textAlignment = CPTTextAlignmentCenter;
    xyAxisSet.xAxis.labelTextStyle = textStyle;
    xyAxisSet.yAxis.labelTextStyle = textStyle;
    
    CPTXYAxis *yAxis = xyAxisSet.yAxis;
    CPTMutableLineStyle *ylineStyle = [CPTMutableLineStyle lineStyle];
    ylineStyle.lineWidth = 1.0f;
    ylineStyle.lineColor = [CPTColor darkGrayColor];
    yAxis.axisLineStyle = ylineStyle;
    
    
    // Line plot with gradient fill
	/*CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
    dataSourceLinePlot.identifier = @"Data Source Plot";
	dataSourceLinePlot.dataLineStyle = nil;
    dataSourceLinePlot.dataSource = self;
	[graph addPlot:dataSourceLinePlot];
	
	CPTColor *areaColor = [CPTColor redColor];//[CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.6];
    CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor:areaColor endingColor:[CPTColor clearColor]];
    areaGradient.angle = -90.0f;
	CPTFill *areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill = areaGradientFill;
    dataSourceLinePlot.areaBaseValue = CPTDecimalFromDouble(200.0);
    
	areaColor = [CPTColor colorWithComponentRed:1.0 green:1.0 blue:1.0 alpha:0.6];
    areaGradient = [CPTGradient gradientWithBeginningColor:[CPTColor clearColor] endingColor:areaColor];
    areaGradient.angle = -90.0f;
	areaGradientFill = [CPTFill fillWithGradient:areaGradient];
    dataSourceLinePlot.areaFill2 = areaGradientFill;
    dataSourceLinePlot.areaBaseValue2 = CPTDecimalFromDouble(400.0);
    */
    
    // OHLC plot
    
    CPTTradingRangePlot *ohlcPlot = [[[CPTTradingRangePlot alloc] initWithFrame:graph.bounds] autorelease];
    ohlcPlot.identifier = @"OHLC";
    ohlcPlot.lineStyle = greenLine;
	/*CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
    whiteTextStyle.color = [CPTColor whiteColor];
	whiteTextStyle.fontSize = 10.0;
	ohlcPlot.labelTextStyle = whiteTextStyle;
	ohlcPlot.labelOffset = 5.0f;
    ohlcPlot.stickLength = 2.0f;
    */ohlcPlot.dataSource = self;
    ohlcPlot.plotStyle = CPTTradingRangePlotStyleOHLC;
    [graph addPlot:ohlcPlot];
    
	// Add plot space for horizontal bar charts
    CPTXYPlotSpace *volumePlotSpace = [[CPTXYPlotSpace alloc] init];
	volumePlotSpace.identifier = @"Volume Plot Space";
    [graph addPlotSpace:volumePlotSpace];
    [volumePlotSpace release];
	
	CPTBarPlot *volumePlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor blackColor] horizontalBars:NO];
    volumePlot.dataSource = self;
    
    lineStyle = [volumePlot.lineStyle mutableCopy];
    lineStyle.lineColor = [CPTColor blackColor];
    volumePlot.lineStyle = lineStyle;
    [lineStyle release];
    CPTFill *fill = [[CPTFill alloc] initWithColor:[CPTColor yellowColor]];
    volumePlot.fill = fill; 
    [fill release];
	volumePlot.barWidth = CPTDecimalFromFloat(1.0f);
    volumePlot.identifier = @"Volume Plot";
    [graph addPlot:volumePlot toPlotSpace:volumePlotSpace];
	
    
    self.datas = [NSMutableArray array];
    
    self.service = [[[StockChartDataService alloc] initWithDelegate:self] autorelease];
    
    //[self.service ]
    
    [super viewDidLoad];
    
}

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
    }
    return self;
}

#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return datas.count;//self.datapuller.financialData.count;;
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
    NSDictionary *data = [datas objectAtIndex:index];
    NSDecimalNumber *num = [NSDecimalNumber zero];
    if ( [plot.identifier isEqual:@"Data Source Plot"] ) {
        if (fieldEnum == CPTScatterPlotFieldX) {
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
        }
        else if (fieldEnum == CPTScatterPlotFieldY) {
            num = [data objectForKey:@"trade"];
            NSAssert(nil != num, @"grrr");
        }
    }
	else if ( [plot.identifier isEqual:@"Volume Plot"] ) {
        if (fieldEnum == CPTBarPlotFieldBarLocation) {
            num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
        }
        else if (fieldEnum == CPTBarPlotFieldBarTip ) {
            num = [data objectForKey:@"amount"];
            NSAssert(nil != num, @"grrr");
        }
    }
    else {
        //CPTTradingRangePlot *rangePlot = (CPTTradingRangePlot*)plot;
        switch ( fieldEnum ) {
            case CPTTradingRangePlotFieldX:
                num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:index + 1];
                break;
            case CPTTradingRangePlotFieldClose:
            	num = [data objectForKey:@"trade"];
                break;
            case CPTTradingRangePlotFieldHigh:
            	num = [data objectForKey:@"high"];
                break;            
            case CPTTradingRangePlotFieldLow:
            	num = [data objectForKey:@"low"];
                break;
            case CPTTradingRangePlotFieldOpen:
            	num = [data objectForKey:@"open"];
                break;
        }
        /*if ([num floatValue]>27.0) {
            rangePlot.lineStyle = redLine;
        }else{
            rangePlot.lineStyle = greenLine;
        }*/
    }
    return num;
}

-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index 
{
	if ( ![(NSString *)plot.identifier isEqualToString:@"OHLC"] )
		return (id)[NSNull null]; // Don't show any label
    else if ( index % 5 ) {
        return (id)[NSNull null];
	}
	else {
		return nil; // Use default label style
	}
}

-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    loaded = YES;
    [self.loadingView removeFromSuperview];
    self.loadingView = nil;
    
	NSArray *newData = [aResult objectForKey:@"quotes"];
    NSArray *temp =[newData filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"amount!=0.0"]];
    NSMutableArray *xLabelTitles = [NSMutableArray array];
    
    self.datas = [NSMutableArray arrayWithArray:temp];
    
    int percent = [[aResult objectForKey:@"degree"] intValue];
    
    if (percent) {
        self.graph.plotAreaFrame.paddingRight = 290.0*(1-percent/100.0);
    }
    float maxTrade=0.0f,minTrade=0.0f,maxAmount=0.0f,minAmount=0.0f;
    
    for (int i=0;i<datas.count;i++) {
        NSDictionary *dict = [datas objectAtIndex:i];
        if (i%2==1) {
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
            float amount = [[[datas objectAtIndex:i-1] objectForKey:@"amount"] floatValue]+[[dict objectForKey:@"amount"] floatValue];
            NSLog(@"amount=%f",amount);
            [tempDict setValue:[NSString stringWithFormat:@"%f",amount] forKey:@"amount"];
            [barChartData addObject:tempDict];
        }
        float low = [[dict objectForKey:@"trade"] floatValue];
        float high = [[dict objectForKey:@"high"] floatValue];
        float amount = [[dict objectForKey:@"amount"] floatValue];
        //NSLog(@"amount=%f",amount);
        if (high > maxTrade) {
            maxTrade = high;
        }
        if (low < minTrade || minTrade==0) {
            minTrade = low;
        }
        if (amount > maxAmount) {
            maxAmount = amount;
        }
        if (amount < minAmount || minAmount==0) {
            minAmount = amount;
        }
        NSString *title = [dict objectForKey:@"ticktime"];
        [xLabelTitles addObject:[title stringByReplacingOccurrencesOfString:@"/" withString:@"-"]];
    }
    
    float margin = maxTrade-minTrade;
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    CPTXYPlotSpace *volumePlotSpace = (CPTXYPlotSpace *)[self.graph plotSpaceWithIdentifier:@"Volume Plot Space"];
	    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(margin?minTrade-margin:minTrade-0.1) length:CPTDecimalFromFloat((2.2*margin)?:0.2)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger([datas count])];
    // Axes
	CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
	
	
	volumePlotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(minAmount) length:CPTDecimalFromFloat(3*(maxAmount-minAmount))];
    volumePlotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger(datas.count)];
    
    //X轴坐标
    int range = datas.count/(percent? (int)MAX(1,percent*5/100.0):5);
    //axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(minTrade-0.5);
    axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromFloat(margin?minTrade-2*margin/3.0:minTrade-0.1);
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(range);
    axisSet.xAxis.minorTicksPerInterval = 0;
    axisSet.xAxis.axisLineStyle = nil;
    //axisSet.xAxis.labelOffset = 10.0f;
    NSMutableArray *labels = [NSMutableArray array];
    int labelsCount = [datas count]/range;
    //NSLog(@"count=%d,labels=%d",[dataArray count],labelsCount);
    for (int i=0; i<labelsCount+1; i++) {
        NSString *title = @"";
        NSLog(@"range=%d,count-1=%d",i*range,[xLabelTitles count]-1);
        if ([xLabelTitles count]>0 && i*range<=[xLabelTitles count]-1) {
            title = [xLabelTitles objectAtIndex:i*range];
        }
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:title textStyle:axisSet.xAxis.labelTextStyle];
        NSNumber *tickLocation = [NSDecimalNumber numberWithInt:i*range];
		newLabel.tickLocation = [tickLocation decimalValue];
		[labels addObject:newLabel];
		[newLabel release];
    }
	axisSet.xAxis.axisLabels =  [NSSet setWithArray:labels];
    
    float labelRange = 0.1;
    if (maxTrade-minTrade > 0.4) {
        labelRange = margin/3;
    }
    
    axisSet.yAxis.majorIntervalLength = CPTDecimalFromCGFloat(labelRange);
    axisSet.yAxis.minorTicksPerInterval = 1;
    axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(@"1.0");
	NSArray *exclusionRanges  = [NSArray arrayWithObjects:
								 [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0) length:CPTDecimalFromCGFloat(minTrade)],
								 nil];
	
	axisSet.yAxis.labelExclusionRanges = exclusionRanges;
	
    [graph reloadData];
}

@end

